package com.banshuibao.bsb_android.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.AdViewPagerAdapter;
import com.banshuibao.bsb_android.adapter.HomeBaseAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.AdModel;
import com.banshuibao.bsb_android.model.CoachModel;
import com.banshuibao.bsb_android.model.ExpertListModel;
import com.banshuibao.bsb_android.model.ExpertResultModel;
import com.banshuibao.bsb_android.model.MediaModel;
import com.banshuibao.bsb_android.model.OfficeModel;
import com.banshuibao.bsb_android.model.UserMessageModel;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshBase;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshListView;
import com.banshuibao.bsb_android.util.DialogUtils;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by zyh on 2018/2/1.
 */

public class BaseHomeFragment extends BaseFragment {

    private PullToRefreshListView pullToRefreshListView;

    private AdViewPagerAdapter pagerAdapter;

    private HomeBaseAdapter homeBaseAdapter;

    private ListView listView;

    private MediaModel.Data mediaData;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private View createHeaderView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.header_ad_view, null);
        ViewPager viewPager = view.findViewById(R.id.vp);
        pagerAdapter = new AdViewPagerAdapter(getActivity(), viewPager);
        viewPager.setAdapter(pagerAdapter);
        return view;
    }

    /**
     * 获取轮播图  0 轮播图 1 直播预告
     **/
    void loadAdImage(final String type) {
        AdModel.BodyList body = new AdModel.BodyList();
        body.setRotationType(type);
        HttpUtil.doPost(Constants.Url.LIST_ROTATION, body, new HttpResponse(getActivity(), AdModel.class) {
            @Override
            public void onResult(Object obj) {
                AdModel adModel = (AdModel) obj;
                if ("0".equals(type)) {
                    if (pagerAdapter != null) {
                        pagerAdapter.setImageViews(adModel.getData());
                    }
                } else {
                    if (homeBaseAdapter != null) {
                        homeBaseAdapter.setAdList(adModel.getData());
                        homeBaseAdapter.notifyHomeBaseAdapter();
                    }
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    /**
     * 政策解读接口
     */
    void loadCoachData() {
        CoachModel.Body body = new CoachModel.Body();
        body.setSinceId(1);
        body.setMaxId(3);
        HttpUtil.doPost(Constants.Url.LIST_POLICY, body, new HttpResponse(getActivity(), CoachModel.class) {
            @Override
            public void onResult(Object obj) {
                CoachModel data = (CoachModel) obj;
                if (homeBaseAdapter != null) {
                    homeBaseAdapter.setCoachList(data.getData());
                    homeBaseAdapter.notifyHomeBaseAdapter();
                }
            }
        });
    }

    /**
     * 获取事务所信息
     **/
    void loadOfficeData() {
        OfficeModel.Body body = new OfficeModel.Body();
        body.setSinceId(1);
        body.setMaxId(5);
        HttpUtil.doPost(Constants.Url.LIST_MOVING, body, new HttpResponse(getActivity(), OfficeModel.class) {
            @Override
            public void onResult(Object obj) {
                OfficeModel officeModel = (OfficeModel) obj;
                if (homeBaseAdapter != null) {
                    homeBaseAdapter.setOfficeList(officeModel.getData());
                    homeBaseAdapter.notifyHomeBaseAdapter();
                }

            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    /**
     * 获取事务所产品
     **/
    void loadOfficeGoodsData() {
        OfficeModel.Body body = new OfficeModel.Body();
        body.setSinceId(1);
        body.setMaxId(4);
        HttpUtil.doPost(Constants.Url.LIST_PRODUCT, body, new HttpResponse(getActivity(), OfficeModel.class) {
            @Override
            public void onResult(Object obj) {
                OfficeModel officeModel = (OfficeModel) obj;
                if (homeBaseAdapter != null) {
                    homeBaseAdapter.setGoodsList(officeModel.getData());
                    homeBaseAdapter.notifyHomeBaseAdapter();
                }

            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    void loadMedia(final String type) {
        MediaModel.Body body = new MediaModel.Body();
        body.setSinceId(1);
        body.setMaxId(4);
        body.setType("all");
        body.setVideoType(type);
        HttpUtil.doPost(Constants.Url.VIDEO_LIST, body, new HttpResponse(getActivity(), MediaModel.class) {
            @Override
            public void onResult(Object obj) {
                MediaModel mediaModel = (MediaModel) obj;
                if (homeBaseAdapter != null) {
                    if (type.equals("1"))
                        homeBaseAdapter.setMediaList(mediaModel.getData());
                    else
                        homeBaseAdapter.setClassMediaList(mediaModel.getData());
                    homeBaseAdapter.notifyHomeBaseAdapter();
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    void loadInterview() {
        MediaModel.Body body = new MediaModel.Body();
        body.setSinceId(1);
        body.setMaxId(1);
        body.setType("all");
        body.setVideoType("3");
        HttpUtil.doPost(Constants.Url.VIDEO_LIST, body, new HttpResponse(getActivity(), MediaModel.class) {
            @Override
            public void onResult(Object obj) {
                MediaModel mediaModel = (MediaModel) obj;
                if (homeBaseAdapter != null) {
                    homeBaseAdapter.setInterviewData(mediaModel.getData().get(0));
                    homeBaseAdapter.notifyHomeBaseAdapter();
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    void loadEventData() {
        MediaModel.Body body = new MediaModel.Body();
        body.setSinceId(1);
        body.setMaxId(2);
        body.setType("all");
        body.setVideoType("4");
        HttpUtil.doPost(Constants.Url.VIDEO_LIST, body, new HttpResponse(getActivity(), MediaModel.class) {
            @Override
            public void onResult(Object obj) {
                MediaModel mediaModel = (MediaModel) obj;
                if (homeBaseAdapter != null) {
                    homeBaseAdapter.setEventMediaList(mediaModel.getData());
                    homeBaseAdapter.notifyHomeBaseAdapter();
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    private Dialog buyDialog;

    void buyMedia(final MediaModel.Data data) {
        if (QuickDoubleClickable.isDoubleClick())
            return;
        this.mediaData = data;
        MediaModel.BuyBody buyBody = new MediaModel.BuyBody();
        buyBody.setUuid(data.getId());
        HttpUtil.doPost(Constants.Url.IS_BUY, buyBody, new HttpResponse(getActivity()) {
            @Override
            public void onResult(Object obj) {
                JSONObject jsonObject = null;
                JSONObject jsonObject1 = null;
                try {
                    jsonObject = new JSONObject((String) obj);
                    jsonObject1 = jsonObject.getJSONObject("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject1 != null) {
                    String type = jsonObject1.optString("type");
                    String vid = jsonObject1.optString("vid");
                    if ("0".equals(type) && !TextUtils.isEmpty(vid)) {
                        if (TextUtils.equals(data.getType(), "1") || TextUtils.equals(data.getType(), "2"))
                            IntentManager.goMediaPlayActivity(getActivity(), vid, Constants.Url.VIDEO, data.getId(), data.getImage());
                        else if (TextUtils.equals(data.getType(), "3")) {
                            IntentManager.goMediaPlayActivity(getActivity(), vid, Constants.Url.INTER_VIDEO, data.getId(), data.getImage());
                        } else
                            IntentManager.goEventMediaPlayActivity(getActivity(), vid, data.getId(), Constants.Url.GAME_VIDEO,data.getImage());
                    } else if (TextUtils.equals("2", type)) {
                        IntentManager.goCheckInActivity(getActivity());
                    } else {
                        buyDialog = DialogUtils.payDialog(getActivity(), "您可以支付" + String.valueOf(data.getPrice()) + "元购买单集或支付365元购买会员卡观看所有视频!",
                                data.getId(), String.valueOf(data.getPrice()), data.getTitle(), 4);
                        if (!buyDialog.isShowing())
                            buyDialog.show();
                      /*  new AlertDialog.Builder(getActivity()).
                                setMessage("购买365会员可以免费观看所有视频,或者支付" + data.getPrice() + "元购买本集").
                                setPositiveButton("购买", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        Intent intent = new Intent(getActivity(), PayActivity.class);
                                        intent.putExtra("flag", 4);
                                        intent.putExtra("content", data.getTitle());
                                        intent.putExtra("price", String.valueOf(data.getPrice()));
                                        intent.putExtra("uuid", data.getId());
                                        startActivityForResult(intent, 200);
                                    }
                                }).setNegativeButton("取消", null).create().show();*/
                    }
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 200:
                    if (mediaData != null)
                        buyMedia(mediaData);
                    break;
            }
        }
    }

    /**
     * 获取专家答疑列表
     */

    void loadAnswer() {
        ExpertListModel listModel = new ExpertListModel();
        listModel.setSinceId(1);
        listModel.setMaxId(3);
        listModel.setType("all");
        HttpUtil.doPost(Constants.Url.EXPERT_ANSWER, listModel, new HttpResponse(getActivity(), ExpertResultModel.class) {
            @Override
            public void onResult(Object obj) {
                ExpertResultModel model = (ExpertResultModel) obj;
                if (homeBaseAdapter != null) {
                    homeBaseAdapter.setAnswerList(model.getData());
                    homeBaseAdapter.notifyHomeBaseAdapter();
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    void loadUserMessage() {
        HttpUtil.doPost(Constants.Url.USER_MESSAGE, null, new HttpResponse(getActivity(), UserMessageModel.class) {
            @Override
            public void onResult(Object obj) {
                UserMessageModel messageModel = (UserMessageModel) obj;
                updateUserMessage(messageModel.getData());
            }
        });
    }

    void updateUserMessage(UserMessageModel.Data user) {
    }

    @Override
    public void onResume() {
        super.onResume();
        if (pagerAdapter != null)
            pagerAdapter.stopAuto(false);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (homeBaseAdapter != null) {
            homeBaseAdapter.stopMedia();
        }
        if (pagerAdapter != null)
            pagerAdapter.stopAuto(true);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (homeBaseAdapter != null) {
                homeBaseAdapter.stopMedia();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (pagerAdapter != null)
            pagerAdapter.clear();
    }

    private void pullComplete() {
        if (pullToRefreshListView != null)
            pullToRefreshListView.onRefreshComplete();
    }

    void setPullToRefreshListView(PullToRefreshListView pullToRefreshListView, HomeBaseAdapter homeBaseAdapter) {
        this.pullToRefreshListView = pullToRefreshListView;
        this.pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        this.pullToRefreshListView.loadBar();
        listView = pullToRefreshListView.getRefreshableView();
        listView.setDivider(null);
        listView.addHeaderView(createHeaderView(), null, false);
        this.homeBaseAdapter = homeBaseAdapter;
        listView.setAdapter(this.homeBaseAdapter);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
       // super.onSaveInstanceState(outState);
    }
}
